package com.lottery.ruok.lottrey.dialog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.MainActivity;
import com.lottery.ruok.lottrey.eventbusObject.GotoBuyPage;
import com.lottery.ruok.lottrey.ui.widget.AlterableProgressBar;
import com.lottery.ruok.lottrey.utils.CustomRotateAnim;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
//活动红包
public class SelectRedPacketDialog extends Activity {
    private final static int REFRESH_GRID = 1;
    @BindView(R.id.red_packet_count)
    TextView redPacketCount;
    @BindView(R.id.red_packet_progress)
    AlterableProgressBar redPacketProgress;
    @BindView(R.id.ll_select_info)
    LinearLayout llSelectInfo;
    private int allowSelectCount = 5;
    private List<Boolean> mIsSelect;
    @BindView(R.id.ib_close)
    Button ibClose;
    @BindView(R.id.select_red_packet_grid)
    GridView selectRedPacketGrid;
    @BindView(R.id.open_red_packet)
    Button mOpenRedPacket;
    private int mMarqueeController = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_GRID:
                    refreshGrid();
                    break;
            }
        }
    };
    private MyAdapter myAdapter;


    private void refreshGrid() {
        myAdapter.setActionOpen(true);
        selectRedPacketGrid.setOnItemClickListener(null);
        mOpenRedPacket.setText("继续投注");
        myAdapter.notifyDataSetChanged();
        mOpenRedPacket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new GotoBuyPage());
                startActivity(new Intent(SelectRedPacketDialog.this,MainActivity.class));
                finish();
                overridePendingTransition(0, R.anim.activity_dialog_out);
            }
        });
    }

    @BindView(R.id.ll_root)
    FrameLayout llRoot;
    private Unbinder bind;
    private Runnable runnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activities_red_packet_layout);
        bind = ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        redPacketCount.setText("请选择5个红包");
        selectRedPacketGrid.setLayoutAnimation(getAnimationController());
        mIsSelect = new ArrayList<>();
        runnable = new Runnable() {
            public void run() {
                mMarqueeController++;
                if (mMarqueeController % 2 == 0) {
                    llRoot.setBackgroundResource(R.mipmap.marquee_bg2);
                } else {
                    llRoot.setBackgroundResource(R.mipmap.marquee_bg1);
                }
                mHandler.postDelayed(this, 1000);
            }
        };

        mHandler.postDelayed(runnable, 1000); // 开始Timer

        //初始化红包grid


        for (int i = 0; i < 10; i++) {
            mIsSelect.add(false);
        }
        myAdapter = new MyAdapter(mIsSelect);
        selectRedPacketGrid.setAdapter(myAdapter);
        selectRedPacketGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (getSelectCount() == allowSelectCount) {
                    if (mIsSelect.get(position) == true) {
                        if (mIsSelect.get(position)) {
                            mIsSelect.set(position, false);
                        } else {
                            mIsSelect.set(position, true);
                        }
                        myAdapter.notifyDataSetChanged();
                    } else {
                        return;
                    }
                } else {
                    if (mIsSelect.get(position)) {
                        mIsSelect.set(position, false);
                    } else {
                        mIsSelect.set(position, true);
                    }
                    myAdapter.notifyDataSetChanged();
                }
                redPacketProgress.setProgress((int) ((getSelectCount() / (double) allowSelectCount) * 100));


                if (getSelectCount() == allowSelectCount) {
                    mOpenRedPacket.setVisibility(View.VISIBLE);
                    llSelectInfo.setVisibility(View.GONE);
                } else {
                    mOpenRedPacket.setVisibility(View.GONE);
                    llSelectInfo.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private double getSelectCount() {
        int count = 0;
        for (Boolean selected : mIsSelect) {
            if (selected) {
                count++;
            }
        }
        return count;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        mHandler.removeCallbacksAndMessages(null);
        mHandler.removeCallbacks(runnable); //停止Timer
    }

    @OnClick({R.id.ib_close, R.id.open_red_packet})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_close:
                finish();
                overridePendingTransition(0, R.anim.activity_dialog_out);
                break;
            case R.id.open_red_packet:
                openRedPacket();
                break;
        }
    }

    private void openRedPacket() {
        // 获取自定义动画实例
        CustomRotateAnim rotateAnim = CustomRotateAnim.getCustomRotateAnim();
        rotateAnim.setDuration(700);
        // 设置为循环播放
        rotateAnim.setRepeatCount(1);
        // 设置为匀速
        rotateAnim.setInterpolator(new LinearInterpolator());
        // 开始播放动画
        for (int i = 0; i < selectRedPacketGrid.getChildCount(); i++) {
            selectRedPacketGrid.getChildAt(i).setAnimation(rotateAnim);
            selectRedPacketGrid.getChildAt(i).startAnimation(rotateAnim);
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(REFRESH_GRID);
            }
        }, 1400);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    class MyAdapter extends BaseAdapter {
        private List<Boolean> isSelect;
        private boolean actionOpen = false;

        public void setActionOpen(boolean actionOpen) {
            this.actionOpen = actionOpen;
        }

        public MyAdapter(List<Boolean> isSelect) {
            this.isSelect = isSelect;
        }

        @Override
        public int getCount() {
            return 9;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(SelectRedPacketDialog.this, R.layout.select_red_packet_layout, null);
            if (actionOpen) {
                if (isSelect.get(position)) {
                    view.setBackgroundResource(R.mipmap.open_select_red_packt_bg);
                } else {
                    view.setBackgroundResource(R.mipmap.unselect_open_red_packet_bg);
                }
            }else {
                if (isSelect.get(position)) {
                    view.setBackgroundResource(R.mipmap.select_red_packet);
                } else {
                    view.setBackgroundResource(R.mipmap.unselect_red_packet);
                }
            }
            return view;
        }
    }

    /**
     * Layout动画
     *
     * @return
     */
    protected LayoutAnimationController getAnimationController() {
        int duration = 200;
        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(duration);
        set.addAnimation(animation);

        animation.setDuration(duration);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(
                set, 0.5f);
        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
        return controller;
    }
}

